package com.onehouse.trigger.http;

import com.onehouse.api.dto.RoomTypeDTO;
import com.onehouse.domain.room.model.RoomTypeEntity;
import com.onehouse.domain.room.service.IRoomTypeService;
import com.onehouse.types.constants.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/room-type")
public class RoomTypeController {

    @Autowired
    private IRoomTypeService roomTypeService;
    
    // 这里可以使用BeanUtils.copyProperties来简化转换，先偷懒
    private RoomTypeDTO convertToDTO(RoomTypeEntity entity) {
        RoomTypeDTO dto = new RoomTypeDTO();
        dto.setTypeId(entity.getTypeId());
        dto.setTypeName(entity.getTypeName());
        dto.setBedType(entity.getBedType());
        dto.setArea(entity.getArea().doubleValue());
        dto.setFacilities(entity.getFacilities());
        dto.setBasePrice(entity.getBasePrice().doubleValue());
        return dto;
    }

    private RoomTypeEntity convertToEntity(RoomTypeDTO dto) {
        return RoomTypeEntity.builder()
                .typeId(dto.getTypeId())
                .typeName(dto.getTypeName())
                .bedType(dto.getBedType())
                .area(BigDecimal.valueOf(dto.getArea()))
                .facilities(dto.getFacilities())
                .basePrice(BigDecimal.valueOf(dto.getBasePrice()))
                .build();
    }

    @Operation(summary = "列出所有房间类型")
    @GetMapping("/list")
    public AjaxResult listAll() {
        return AjaxResult.success(
            roomTypeService.listAllRoomType().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList())
        );
    }

    @Operation(summary = "创建新的房间类型")
    @PostMapping("/create")
    public AjaxResult createRoomType(@RequestBody RoomTypeDTO roomTypeDTO) {
        try {
            roomTypeService.createRoomType(convertToEntity(roomTypeDTO));
            return AjaxResult.success();
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Operation(summary = "更新房间类型")
    @PutMapping("/update")
    public AjaxResult updateRoomType(@RequestBody RoomTypeDTO roomTypeDTO) {
        try {
            roomTypeService.updateRoomType(convertToEntity(roomTypeDTO));
            return AjaxResult.success();
        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Operation(summary = "删除房间类型")
    @DeleteMapping("/delete/{typeId}")
    public AjaxResult removeRoomType(@PathVariable Long typeId) {
        try {
            roomTypeService.removeRoomType(typeId);
            return AjaxResult.success();
        } catch (IllegalStateException e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
